/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package sharefileclient;

import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import sharefileinterface.FilePart;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import sharefileinterface.FileShared;
import sharefileinterface.StatedFileShare;

/**
 *
 * @author anwedo
 */
public class ClientGUI extends javax.swing.JFrame {

    final public static int PART_SIZE = 1000000;

    public sharefileinterface.ShareFileInterface server;
    public LinkedHashMap<Integer, ArrayList<FilePart>> fileShareList;

    /**
     * Creates new form ClientGUI
     */
    public ClientGUI() {
        initComponents();
        tbFileList.setVisible(false);
        fileShareList = new LinkedHashMap<>();
        InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
        } catch (UnknownHostException ex) {
            Logger.getLogger(ClientGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
        //String ipAddr = addr.getHostAddress();
        ListenRequestThread listen = new ListenRequestThread(this);
        listen.start();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tbFileList = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        txtSearch = new javax.swing.JTextField();
        btnSearch = new javax.swing.JButton();
        btnDownload = new javax.swing.JButton();
        prgDownload = new javax.swing.JProgressBar();
        btnShow = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        mniJoin = new javax.swing.JMenuItem();
        mniRegist = new javax.swing.JMenuItem();
        mniExit = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Client ");

        tbFileList.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tbFileList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tbFileList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbFileListMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbFileList);

        jLabel1.setText("Search file: ");

        txtSearch.setColumns(10);

        btnSearch.setText("Search");
        btnSearch.setEnabled(false);
        btnSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchActionPerformed(evt);
            }
        });

        btnDownload.setText("Download");
        btnDownload.setEnabled(false);
        btnDownload.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDownloadActionPerformed(evt);
            }
        });

        btnShow.setText("View Folder");
        btnShow.setEnabled(false);
        btnShow.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnShowActionPerformed(evt);
            }
        });

        jMenu1.setText("File");

        mniJoin.setText("Join System");
        mniJoin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mniJoinActionPerformed(evt);
            }
        });
        jMenu1.add(mniJoin);

        mniRegist.setText("Register file");
        mniRegist.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mniRegistActionPerformed(evt);
            }
        });
        jMenu1.add(mniRegist);

        mniExit.setText("Exit");
        mniExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mniExitActionPerformed(evt);
            }
        });
        jMenu1.add(mniExit);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(53, 53, 53)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(btnShow)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnSearch)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnDownload)
                        .addGap(0, 34, Short.MAX_VALUE))
                    .addComponent(prgDownload, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(txtSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnSearch)
                            .addComponent(btnDownload))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(prgDownload, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(btnShow))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 231, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    //list file in directory function
    private static Vector<FileShared> rfid = new Vector<>();

    private static Vector<FileShared> fileInDir(File dir, File root) {
        for (File f : dir.listFiles()) {
            if (f.isDirectory()) {
                fileInDir(f, root);
            } else if (f.isFile()) {
                String filename = f.getName();
                while (!f.getParentFile().equals(root)) {
                    filename = f.getParentFile().getName() + "/" + filename;
                    f = f.getParentFile();
                }
                filename = root.getName() + "/" + filename;
                FileShared fs = new FileShared(filename, f.length());
                rfid.add(fs);
            }
        }
        return rfid;
    }

    //copy function
    public static final void copy(File source, File destination) throws IOException {
        if (source.isDirectory()) {
            copyDirectory(source, destination);
        } else {
            copyFile(source, destination);
        }
    }

    public static final void copyDirectory(File source, File destination) throws IOException {
        if (!source.isDirectory()) {
            throw new IllegalArgumentException("Source (" + source.getPath() + ") must be a directory.");
        }

        if (!source.exists()) {
            throw new IllegalArgumentException("Source directory (" + source.getPath() + ") doesn't exist.");
        }

        if (destination.exists()) {
//            throw new IllegalArgumentException("Destination (" + destination.getPath() + ") exists.");
            JOptionPane.showMessageDialog(null, "Destination (" + destination.getPath() + ") exists.");
        }

        destination.mkdirs();
        File[] files = source.listFiles();

        for (File file : files) {
            if (file.isDirectory()) {
                copyDirectory(file, new File(destination, file.getName()));
            } else {

                copyFile(file, new File(destination, file.getName()));
            }
        }
    }

    public static final void copyFile(File source, File destination) throws IOException {
//        FileChannel targetChannel;
//        try (FileChannel sourceChannel = new FileInputStream(source).getChannel()) {
//            targetChannel = new FileOutputStream(destination).getChannel();
//            sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);
//        }
//        targetChannel.close();
        int n = 2048;
        try (OutputStream out = new FileOutputStream(destination)) {
            byte[] buf = new byte[n];
            FileInputStream in = new FileInputStream(source);
            int b = 0;
            while ((b = in.read(buf)) >= 0) {
                out.write(buf, 0, b);
                out.flush();
            }
        }
    }

    private String getComputerName() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException ex) {
            Logger.getLogger(ClientGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "unknown";
    }

    public String getmacAdd() {
        String radd = "";
        InetAddress ip;
        try {
            ip = InetAddress.getLocalHost();
            System.out.println("Current IP address : " + ip.getHostAddress());

            NetworkInterface network = NetworkInterface.getByInetAddress(ip);

            byte[] mac = network.getHardwareAddress();

//            System.out.print("Current MAC address : ");
//            System.out.println("mac leng =" + mac.length);
            //convert to hexa 128 bit 
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mac.length; i++) {
                sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
            }
            radd = sb.toString();
            System.out.println(sb.toString());

        } catch (UnknownHostException | SocketException e) {
        }
        return radd;
    }
    private void mniJoinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniJoinActionPerformed
        // TODO add your handling code here:
        serverIP = JOptionPane.showInputDialog(rootPane, "Enter host IP.");
        if (serverIP != null) {
            try {
                // TODO code application logic here
                if (serverIP.equals("")) {
                    serverIP = "localhost";
                }
                rmiurl = "rmi://" + serverIP + ":1080/Shareserver";
                server = (sharefileinterface.ShareFileInterface) Naming.lookup(rmiurl);
                if (server.checkJoin(this.getmacAdd(), this.getComputerName()) == 1) {
                    mniJoin.setEnabled(false);
                    btnDownload.setEnabled(true);
                    btnSearch.setEnabled(true);
                    tbFileList.setVisible(true);
                    searchFile("");
                    JOptionPane.showMessageDialog(rootPane, "Connect successful!");
                } else {
                    JOptionPane.showMessageDialog(rootPane, "Please check your connection!");
                }
            } catch (NotBoundException | MalformedURLException | RemoteException ex) {
                System.out.println(ex.getMessage());
                JOptionPane.showMessageDialog(rootPane, "Please check your connection!", "Connect unsuccess", JOptionPane.WARNING_MESSAGE);
            }
        }
    }//GEN-LAST:event_mniJoinActionPerformed

    private void mniRegistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniRegistActionPerformed
        try {
            // TODO add your handling code here:
            JFileChooser fc = new JFileChooser();
            fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            fc.showOpenDialog(this);
            File f = fc.getSelectedFile();
            // System.out.println("File name: " + f.getName() + ", size: " + f.length() / 1024 + "KB, path: " + f.getPath());
            //save file to share folder
            int n = 2048;
            String currentDirectory = System.getProperty("user.dir");
            File shareFolder = new File(currentDirectory, "share");
            if (!shareFolder.exists()) {
                shareFolder.mkdir();
            }
            //check choosen file is file or folder
            if (f.isFile()) {
                InputStream in;
                //copy file to share folder
                File sf = new File(shareFolder.getPath(), f.getName());
                try (OutputStream out = new FileOutputStream(sf)) {
                    byte[] buf = new byte[n];
                    in = new FileInputStream(f);
                    int b;
                    while ((b = in.read(buf)) >= 0) {
                        out.write(buf, 0, b);
                        out.flush();
                    }
                }
                try {
                    in.close();
                } catch (IOException ex) {
                    Logger.getLogger(ClientGUI.class.getName()).log(Level.SEVERE, null, ex);
                }
                //copy success             

                //regist file to server
                server = (sharefileinterface.ShareFileInterface) Naming.lookup(rmiurl);
                int fid = server.registFile(f.getName(), getmacAdd(), f.length());
                
                if (fid != 0) {
                    prepareFilePart(fid, f.getName());
                    int hasTotalPart = (int) (f.length() / PART_SIZE + 1);
                    //Thong bao den server
                    server.hasFilePart(getmacAdd(), fid, hasTotalPart);
                    searchFile("");
                    
                    JOptionPane.showMessageDialog(rootPane, "Register successful!");
                } else {
                    JOptionPane.showMessageDialog(rootPane, "Register fail!");
                }

            } else if (f.isDirectory()) {
                //
                File des = new File(shareFolder, f.getName());

                copy(f, des);
                //regist directory to server
                server = (sharefileinterface.ShareFileInterface) Naming.lookup(rmiurl);
                //Vector<FileShared> lfs = new Vector<>();
                //regist new directory
                lfs = fileInDir(des, des);
                if (server.registDirectory(f.getName(), getmacAdd(), f.length(), lfs) == 1) {
                    JOptionPane.showMessageDialog(rootPane, "Register successful!");
                }
            }
        } catch (HeadlessException | IOException | NotBoundException ex) {
            Logger.getLogger(ClientGUI.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_mniRegistActionPerformed

    private void searchFile(String key) {
        try {
            // TODO code application logic here
            server = (sharefileinterface.ShareFileInterface) Naming.lookup(rmiurl);
            Vector<String> columnName = new Vector<>();
            columnName.add("File Name");
            columnName.add("Owner");
            columnName.add("Type");
            columnName.add("Size");
            Vector<Vector> tableData = new Vector<>();
            filesshared = server.getFileList(key);
            UpdateMappingFileIDName();
            for (StatedFileShare fs : filesshared) {
                Vector v = new Vector();
                v.addElement(fs.getFilename());
                v.addElement(fs.getSenderName());
                if ("f".equals(fs.getType())) {
                    v.addElement("File");
                } else {
                    v.addElement("Directory");
                }
                v.addElement(fs.getSize());
                // System.out.println("name: " + fs.getFilename());

                tableData.addElement(v);
            }
            DefaultTableModel tableModel = new DefaultTableModel(tableData, columnName);
            tbFileList.setModel(tableModel);
        } catch (NotBoundException | MalformedURLException | RemoteException ex) {
            System.out.println(ex.getMessage());
            JOptionPane.showMessageDialog(rootPane, "Please check your connection!", "Connect unsuccess", JOptionPane.WARNING_MESSAGE);
        }
    }

    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
        // TODO add your handling code here:
        if (txtSearch.getText().isEmpty()) {
            searchFile("");
        } else {
            searchFile(txtSearch.getText());
        }
    }//GEN-LAST:event_btnSearchActionPerformed

    public int hasRealPart(ArrayList<FilePart> filePartList) {
        int totalPart = 0;
        for (FilePart part : filePartList) {
            if (part.data != null) {
                totalPart++;
            } else {
                break;
            }
        }
        return totalPart;
    }

    private String filterIPFromList(Vector<String> ipl) {
        String rip = "";
        for (String string : ipl) {
            try {
                InetAddress host = InetAddress.getByName(string);
                if (host.isReachable(6000)) {
                    rip = string;

                } else {
                    sharefileinterface.ShareFileInterface server = (sharefileinterface.ShareFileInterface) Naming.lookup(rmiurl);
                    server.changeStatusForIP(rip);
                }
            } catch (UnknownHostException ex) {
                Logger.getLogger(ClientGUI.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException | NotBoundException ex) {
                Logger.getLogger(ClientGUI.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return rip;
    }

    private void btnDownloadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDownloadActionPerformed
        // TODO add your handling code here:
        try {
            int s = tbFileList.getSelectedRow();
            if (s != -1) {
                //download
                StatedFileShare sfs = filesshared.get(s);
                if (sfs.getSender().equals(getmacAdd())) {
                    JOptionPane.showMessageDialog(rootPane, "File already exist in your share folder.");
                    return;
                }
                switch (sfs.getType()) {
                    case "f":
                        try {
                            server = (sharefileinterface.ShareFileInterface) Naming.lookup(rmiurl);

                            if ("f".equals(sfs.getType())) {
                                //start download theard
                                Thread dth = new DownloadThread(this, "localhost", sfs.getFid(), sfs.getFilename(), sfs.getSize(), prgDownload);
                                dth.start();
                            }
                        } catch (NotBoundException | MalformedURLException | RemoteException ex) {
                            Logger.getLogger(ClientGUI.class.getName()).log(Level.SEVERE, null, ex);
                            JOptionPane.showMessageDialog(rootPane, "Please check your connection!", "Connect unsuccess", JOptionPane.WARNING_MESSAGE);
                        }
                        break;

                    case "d":
                        try {
                            //get list file
                            server = (sharefileinterface.ShareFileInterface) Naming.lookup(rmiurl);
                            Vector<String> fileList = server.folderContent(sfs.getFid());
                            //get share directory
                            String currentDirectory = System.getProperty("user.dir");
                            File shareFolder = new File(currentDirectory, "share");
                            if (!shareFolder.exists()) {
                                shareFolder.mkdir();
                            }
                            for (int k = 0; k < fileList.size(); k++) {
                                String sf = fileList.get(k);
                                String sfp[] = sf.split("/");
                                if (sfp.length > 1) {
                                    File par = new File(shareFolder, sfp[0]);
                                    if (!par.exists()) {
                                        par.mkdir();
                                    }
                                    for (int i = 1; i < sfp.length - 1; i++) {
                                        File newFolder = new File(par, sfp[i]);
                                        par = newFolder;
                                        if (!par.exists()) {
                                            par.mkdir();
                                        }
                                    }
                                    String ip = filterIPFromList(server.getIPListByFid(sfs.getFid()));
                                    int size = server.getFileSize(sfs.getFid(), k);
                                    //System.out.println("ip:"+ip+":size:"+size+":name:"+sf);

                                    if ("f".equals(sfs.getType())) {
                                        //start download theard
                                        Thread dth = new DownloadThread(this, "localhost", sfs.getFid(), sfs.getFilename(), size, prgDownload);
                                        dth.start();
                                    }
                                }
                            }
                        } catch (NotBoundException | MalformedURLException | RemoteException ex) {
                            Logger.getLogger(ClientGUI.class.getName()).log(Level.SEVERE, null, ex);
                            JOptionPane.showMessageDialog(rootPane, "Please check your connection!", "Connect unsuccess", JOptionPane.WARNING_MESSAGE);
                        }
                        break;
                }
            }
        } catch (HeadlessException ex) {
        }

	}//GEN-LAST:event_btnDownloadActionPerformed

    private void tbFileListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbFileListMouseClicked
        // TODO add your handling code here:
        try {
            int i = tbFileList.getSelectedRow();
            if (i != -1) {
                StatedFileShare sfs = filesshared.get(i);
                if ("d".equals(sfs.getType())) {
                    btnShow.setEnabled(true);
                } else {
                    btnShow.setEnabled(false);
                }
            } else {
                btnShow.setEnabled(false);
            }
        } catch (Exception e) {
            //  JOptionPane.showMessageDialog(rootPane, "Please check your connection!", "Connect unsuccess", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_tbFileListMouseClicked

    private void btnShowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnShowActionPerformed
        try {
            // TODO add your handling code here:
            sharefileinterface.ShareFileInterface server = (sharefileinterface.ShareFileInterface) Naming.lookup(rmiurl);
            int tbi = tbFileList.getSelectedRow();
            Vector<String> fl = server.folderContent(filesshared.get(tbi).getFid());
            ViewFolderForm vff = new ViewFolderForm(fl);
            vff.setVisible(true);
        } catch (NotBoundException | MalformedURLException | RemoteException ex) {
            Logger.getLogger(ClientGUI.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_btnShowActionPerformed

    private void mniExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniExitActionPerformed
        try {
            // TODO add your handling code here:
            sharefileinterface.ShareFileInterface server = (sharefileinterface.ShareFileInterface) Naming.lookup(rmiurl);
            int tbi = server.changeStatusWithMac(getmacAdd());
            if (tbi == 1) {
                System.exit(1);
            }
        } catch (NotBoundException | MalformedURLException | RemoteException ex) {
            Logger.getLogger(ClientGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_mniExitActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ClientGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ClientGUI().setVisible(true);
            }
        });
    }

    public void UpdateMappingFileIDName() {
        mappingFileIDName = new LinkedHashMap<>();
        for (StatedFileShare file : filesshared) {
            mappingFileIDName.put(new Integer(file.getFid()), file.getFilename());
        }
    }

    public LinkedHashMap<Integer, String> getMappingFileIDName() {
        return mappingFileIDName;
    }

    public void prepareFilePart(int fid, String fileGet) {
        //chuan bi phan file
        ArrayList<FilePart> partList = fileShareList.get(new Integer(fid));
        if (partList == null) {
            //check file
            String currentDirectory = System.getProperty("user.dir");
            File shareFolder = new File(currentDirectory, "share");
            if (!shareFolder.exists()) {
                shareFolder.mkdir();
            }

            File sf = new File(shareFolder.getPath(), fileGet);
            if (!sf.exists()) {
                return;
            }
            String filePath = sf.getPath();
            int totalSizeRead;
            byte[] packet = new byte[PART_SIZE];
            try (FileInputStream fis = new FileInputStream(filePath)) {
                partList = new ArrayList<>();
                int count = 0;
                FilePart part;
                while ((totalSizeRead = fis.read(packet, 0, packet.length)) >= 0) {
                    if (packet.length > totalSizeRead) {
                        byte[] packetCopy = new byte[totalSizeRead];
                        System.arraycopy(packet, 0, packetCopy, 0, totalSizeRead);
                        part = new FilePart(count++, "", "", packetCopy);
                    } else {
                        part = new FilePart(count++, "", "", packet);
                    }
                    partList.add(part);
                }
                fileShareList.put(new Integer(fid), partList);
                fis.close();
            } catch (IOException ex) {
                Logger.getLogger(RMIClient.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDownload;
    private javax.swing.JButton btnSearch;
    private javax.swing.JButton btnShow;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JMenuItem mniExit;
    private javax.swing.JMenuItem mniJoin;
    private javax.swing.JMenuItem mniRegist;
    private javax.swing.JProgressBar prgDownload;
    private javax.swing.JTable tbFileList;
    private javax.swing.JTextField txtSearch;
    // End of variables declaration//GEN-END:variables
    private Vector<StatedFileShare> filesshared = null;
    private LinkedHashMap<Integer, String> mappingFileIDName = null;
    private Vector<FileShared> lfs = new Vector<>();
    private File sourceFolder = null;
    private String serverIP;
    private String rmiurl = "rmi://localhost:1080/Shareserver";
}
